#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <stdio.h>
#include <time.h>
#include "cJSON/cJSON.h"
#include "agreement/agreement.h"
#include "DateTime.h"
#include "agreement/encrypt.h"
#include "agreement/upload.h"
#include "json_list.h"
#include "viewwindow.h"
#include "Qt/multithread.h"
//#include "MySql.h"
#include "sql.h"

extern "C" int CJSON_CDECL cJSON_main(void);
extern "C" int utc_main(void);

#include "thread_list.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    viewer = nullptr;
//    time_t timer = time(NULL);
//    printf("ctime is [%d] %s\n", timer, ctime(&timer));//得到日历时间
//    fflush(stdout);
//    cJSON_main();
//    fflush(stdout);
    ui->lineEdit_IP->setText("39.108.72.130");
#if 1
    ui->lineEdit_PORT->setText("9910");
#else
    ui->lineEdit_PORT->setText("IP端口不校验，请确保正确！");
#endif
    ssl = SSL_INFO;
    ui->radioButton_info->setChecked(true);
    ui->radioButton_SM2->setEnabled(false);
    //rsa_test();
    ThreadClient=nullptr;
    _controllerClient=nullptr;
    ThreadDownload = nullptr;
    _controllerDownload=nullptr;
}

MainWindow::~MainWindow()
{
    workThread::stop();  // 所有线程停止
    MultiThread::stop();
    QThread::msleep(500);
    if(nullptr != viewer) delete viewer;
    viewer = nullptr;
    //delete ui;
    if(nullptr!=ui) delete ui;
    ui = nullptr;
}

void MainWindow::start_client()
{
    qDebug() << "client start";
#if 0
    workerThread = new ControllerThread();
    connect(workerThread->worker, &workThread::resultReady, this, &MainWindow::handleResults);
    //connect(workerThread, &Client::finished, workerThread, &QObject::deleteLater);
    workThread::IP(ui->lineEdit_IP->text(), ui->lineEdit_PORT->text().toInt());
    SocketClient::set_ssl(ssl);
    workThread::start();
    workThread::mode(WORK_CLIENT);
    workerThread->start();
#else
    if(nullptr!=ThreadClient) delete ThreadClient;
    if(nullptr!=_controllerClient) delete _controllerClient;
    ThreadClient=new SocketThreadClient();
    ThreadClient->IP(ui->lineEdit_IP->text(), ui->lineEdit_PORT->text().toInt());
    OBDII_4G::set_ssl(ssl);
    //connect(viewer, SIGNAL(resultReady(const QString &result, const void* data)), this, SLOT(handleResults(const QString &result, const void* data)));
    connect(ThreadClient, &MultiThread::resultReady, this, &MainWindow::handleThread);
    _controllerClient = new ControllerMultiThread(ThreadClient);
    _controllerClient->start("Client Thread");
#endif
}

void MainWindow::start_download()
{
    qDebug() << "download start";
#if 0
    workerThread = new ControllerThread();
    connect(workerThread->worker, &workThread::resultReady, this, &MainWindow::handleResults);
    //connect(workerThread, &Client::finished, workerThread, &QObject::deleteLater);
    workThread::IP(ui->lineEdit_IP->text(), ui->lineEdit_PORT->text().toInt());
    SocketClient::set_ssl(ssl);
    workThread::start();
    workThread::mode(WORK_DOWNLOAD);
    workerThread->start();
#else
    if(nullptr!=ThreadDownload) delete ThreadDownload;
    if(nullptr!=_controllerClient) delete _controllerClient;
    ThreadDownload=new SocketThreadDownload();
    ThreadDownload->IP(ui->lineEdit_IP->text(), ui->lineEdit_PORT->text().toInt());
    OBDII_4G::set_ssl(ssl);
    //connect(viewer, SIGNAL(resultReady(const QString &result, const void* data)), this, SLOT(handleResults(const QString &result, const void* data)));
    connect(ThreadDownload, &MultiThread::resultReady, this, &MainWindow::handleThread);
    _controllerDownload = new ControllerMultiThread(ThreadDownload);
    _controllerDownload->start("Download Thread");
#endif
}

void MainWindow::handleThread(const QString result, const void *data)
{
    //qDebug() << "client:" << result;
    ui->label_Ready->setText(result);
}

void MainWindow::on_pushButton_clicked()
{
    //int len = 0;
    //fflush(stdout);
    //time_t timer = time(NULL);
//    time_t        times     = 0;
//    double        mjd       = 0.0;
//    DateTime      utctime   = {.year = 1970, .month = 1, .day = 1, .hour = 0, .minute = 0, .second = 0};
//    DateTime      localtime = {.year = 1970, .month = 1, .day = 1, .hour = 8, .minute = 0, .second = 0};
//    DateTime      gpstime   = {.year = 1970, .month = 1, .day = 1, .hour = 0, .minute = 0, .second = 0};
//    //time(&times);
//    times = timer;

//    if(times > INT32_MAX)
//    {
//      utctime = GregorianCalendarDateAddSecond(utctime, INT32_MAX);
//      utctime = GregorianCalendarDateAddSecond(utctime, (int)(times - INT32_MAX));
//    }
//    else
//    {
//      utctime = GregorianCalendarDateAddSecond(utctime, (int)times);
//    }

//    mjd       = GregorianCalendarDateToModifiedJulianDate(utctime);
//    localtime = GregorianCalendarDateAddHour(utctime, 8);
//    gpstime   = GregorianCalendarDateAddSecond(utctime, 18);
//    //gpstimews = GregorianCalendarDateToGpsWeekSecond(gpstime);


//    printf("Local | %d-%.2d-%.2d %.2d:%.2d:%.2d | timezone UTC+8\n",
//           localtime.year, localtime.month, localtime.day,
//           localtime.hour, localtime.minute, localtime.second);

//    printf("UTC   | %d-%.2d-%.2d %.2d:%.2d:%.2d | MJD %.5f\n",
//           utctime.year, utctime.month, utctime.day,
//           utctime.hour, utctime.minute, utctime.second,
//           mjd);
//    fflush(stdout);
    //agreement_init();
    agreement_test();
    //utc_main();
    //start_local_test();
    //rsa_test();
    //rsa_main();
    //upload_test();
}

void MainWindow::on_pushButton_work_clicked()
{
    start_client();
    ui->groupBox_ssl->setEnabled(false);
}

void MainWindow::on_radioButton_info_clicked()
{
    ssl = SSL_INFO;
}

void MainWindow::on_radioButton_RSA_clicked()
{
    ssl = SSL_RSA;
}

void MainWindow::on_radioButton_SM2_clicked()
{
    ssl = SSL_SM2;
}

void MainWindow::on_pushButton_download_clicked()
{
    start_download();
}
#include "dialogcfg.h"
void MainWindow::on_pushButton_cfg_clicked()
{
#if 0
    create_cfg("OBD.cfg");
#else
    DialogCFG *cfg = new DialogCFG();
    cfg->setModal(true);
    cfg->show();
#endif
}
#include "dialogdevice.h"
void MainWindow::on_pushButton_list_clicked()
{
#if 0
    create_list("Device.list");
    json_list_add("Device.list", "102905420158", JSON_LIST_DEV);
    json_list_add("Device.list", "102905420158", JSON_LIST_UP);
    json_list_del("Device.list", "102905420148", JSON_LIST_DEV);
    //json_list_del("Device.list", "102905420148", JSON_LIST_UP);
    qDebug("json_list_search:%d \n", json_list_search("Device.list", "102905420148", JSON_LIST_UP));
    qDebug("json_list_search:%d \n", json_list_search("Device.list", "102905420128", JSON_LIST_UP));
#else
    DialogDevice *device = new DialogDevice();
    //device.accept();
    device->setModal(true);
    device->show();
#endif
}

void MainWindow::on_pushButton_test_clicked()
{
    thread_list_init();
    struct device_list* device = get_thread_free();
    online_thread_add(device);
    online_thread_free(device);
}

void MainWindow::on_pushButton_Stop_clicked()
{
    workThread::stop();  // 所有线程停止
    MultiThread::stop();
}



void MainWindow::on_pushButton_Viewer_clicked()
{
//    ViewWindow viewer;
//    viewer.show();
    viewer = new ViewWindow();
    //connect(viewer, SIGNAL(sigClose(const QString obj)), this, SLOT(slotsClose(const QString obj)));
    viewer->show();
#if 0
    static int multi=0;
    if(0==multi)
    {
        MultiThreadTest_Start();
        multi = 1;
    }
    else
    {
        MultiThreadTest_Stop();
        multi = 0;
    }
#endif
}

void MainWindow::on_pushButton_Multi_clicked()
{
#if 0
    int i;
    for(i=0; i<200; i++)
    {
//        if(nullptr!=ThreadClient) delete ThreadClient;
//        if(nullptr!=_controllerClient) delete _controllerClient;
        ThreadClient=new SocketThreadClient();
        ThreadClient->IP(ui->lineEdit_IP->text(), ui->lineEdit_PORT->text().toInt());
        OBDII_4G::set_ssl(ssl);
        //connect(viewer, SIGNAL(resultReady(const QString &result, const void* data)), this, SLOT(handleResults(const QString &result, const void* data)));
        connect(ThreadClient, &MultiThread::resultReady, this, &MainWindow::handleThread);
        _controllerClient = new ControllerMultiThread(ThreadClient);
        _controllerClient->start("Client Thread..."+QString::number(i));
        QThread::msleep(50);
    }
#endif
    // 并发测试
    thread_pond=new Thread_Pond();
    thread_pond->IP(ui->lineEdit_IP->text(), ui->lineEdit_PORT->text().toInt());
    OBDII_4G::set_ssl(ssl);
    //connect(viewer, SIGNAL(resultReady(const QString &result, const void* data)), this, SLOT(handleResults(const QString &result, const void* data)));
    connect(thread_pond, &MultiThread::resultReady, this, &MainWindow::handleThread);
    _controller_pond = new ControllerMultiThread(thread_pond);
    _controller_pond->start("Thread Pond");
}

void MainWindow::on_pushButton_VIN_clicked()
{
    char vin[32];
    static const char vin_path[] = "./upload/vin.list";
    static const char sn[] = "102906420029";
    ui->label_Ready->clear();
    create_vin_list(vin_path);
    ui->label_Ready->setText("创建列表文件 \""+QString(vin_path)+"\"成功\n");
    memset(vin, 0, sizeof (vin));
    if(0==create_vin_search(vin_path, sn, vin))
    {
        ui->label_Ready->setText(ui->label_Ready->text()+"数据获取成功\n");
    }
    ui->label_Ready->setText(ui->label_Ready->text()+"SN:"+QString(sn)+"VIN:"+QString(vin));
}

void MainWindow::on_pushButton_sql_clicked()
{
    MySqlInit();
    insert_item_string("vin", "VINVIN-1234567890");
    insert_item_int("prot", 0);
    insert_item_int("mil", 1);
    insert_item_int("status", 2);
    insert_item_int("ready", 3);
    insert_item_string("svin", "OBDII-123456789");
    insert_item_string("cin", "Jul 5 2019 11:17");
    insert_item_string("iupr", "0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 ");
    insert_item_int("fault_total", 2);
    insert_item_string("fault", "0002 0003");
    insert_item("speed", 0.1);
    insert_item("kpa", 0.2);
    insert_item("nm", 0.3);
    insert_item("nmf", 0.4);
    insert_item("rpm", 0.5);
    insert_item("Lh", 0.6);
    insert_item("ppm_up", 0.7);
    insert_item("ppm_down", 0.8);
    insert_item("urea", 0.9);
    insert_item("kgh", 1.0);
    insert_item("SCR_in", 2.0);
    insert_item("SCR_out", 3.0);
    insert_item("DPF", 4.0);
    insert_item("coolant_temp", 5.0);
    insert_item("tank", 6.0);
    insert_item_int("gps_status", 7);
    insert_item("lat", 8.0);
    insert_item("lng", 9.0);
    insert_item("mil_total", 10.0);
    insert_item_int("Nm_mode", 20);
    insert_item("accelerator", 30.0);
    insert_item("oil_consume", 40.0);
    insert_item("urea_temp", 50.0);
    insert_item("urea_actual", 60.0);
    insert_item("urea_total", 70.0);
    insert_item("gas_temp", 80.0);
    insert_item_int("version", 6789);
    insert_sql();
    MySqlClose();
}
